from common import *
import tkinter as tk
from tkinter import ttk


class CheckApp(Window):
    def __init__(self, ddt):
        super().__init__()
        self.root = ddt
        self.window = ddt.app
        self.title = "选择应用程序"
        self.WIDTH = 0
        self.HEIGHT = 0

        """变量"""
        self.app_name = tk.StringVar()
        self.resolving_power = tk.StringVar()
        self.resolving_power_values = ["540x960", "600x800", "720x1280", "800x600",
                                       "960x540", "1080x1920", "1280x720", "1920x1080"]

        """加载组件"""
        self.set_window()

    def on_closing(self):
        self.root.app = None
        self.window.destroy()

    def set_function(self):
        """重写功能"""
        # 关闭事件
        self.window.protocol("WM_DELETE_WINDOW", self.on_closing)
        # 禁止拉伸
        self.window.resizable(0, 0)
        # 去掉窗口最大化最小化按钮，只保留关闭
        self.window.attributes("-toolwindow", 2)
        # 选择功能
        app_values = get_apps()
        self.window.wm_attributes('-topmost', 1)
        app_label = tk.Label(self.window, text="选择应用程序")
        app_combobox = ttk.Combobox(self.window, state="readonly", values=app_values, textvariable=self.app_name)
        resolving_power_label = tk.Label(self.window, text="选择分辨率")
        resolving_power_combobox = ttk.Combobox(self.window, state='readonly', values=self.resolving_power_values,
                                                textvariable=self.resolving_power)
        app_button = tk.Button(self.window, text="保存设置", command=self.save_app)
        app_label.grid(row=0, column=0)
        app_combobox.grid(row=0, column=1)
        resolving_power_label.grid(row=1, column=0)
        resolving_power_combobox.grid(row=1, column=1)
        app_button.grid(row=2, column=0, columnspan=2)

        resolving_power_combobox.bind('<<ComboboxSelected>>', self.move_app)

    def move_app(self, event):
        """根据分辨率移动并调整窗口"""
        hwnd = win32gui.FindWindow(None, self.app_name.get())
        win32gui.SetWindowPos(hwnd, win32con.HWND_NOTOPMOST, 0, 0, int(self.resolving_power.get().split("x")[0]),
                              int(self.resolving_power.get().split("x")[1]), win32con.SWP_SHOWWINDOW)

    def save_app(self):
        """保存分辨率设置至配置文件"""
        if self.resolving_power.get() == "":
            self.root.warn_log("还没有选择分辨率，无法保存")
            return 0
        self.root.project.config.resolving_power = self.resolving_power.get()
        self.root.project.config.app_name = self.app_name.get()
        self.root.project.config.save()
        self.root.info_log(f"分辨率设置已保存：{self.resolving_power.get()}")
        self.root.project.config.read_config()
        self.window.destroy()
